import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText, } from '@ant-design/pro-components';
import { FormattedMessage, Helmet, SelectLang, useIntl, useModel, useRequest, } from '@umijs/max';
import { App, Flex, Form, Image, Tabs } from 'antd';
import { createStyles } from 'antd-style';
import React, { useCallback, useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import { login } from '@/services/ant-design-pro/api';
import Settings from '../../../../config/defaultSettings';
import { setToken } from '@/utils/request/token';
import loginStyle from './login.module.css';
import { useDebounceFn } from 'ahooks';
import { getCaptcha } from '@/services/ant-design-pro/login';

const useStyles = createStyles(( {token} ) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        'url(\'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr\')',
      backgroundSize: '100% 100%',
    },
  };
});


const Lang = () => {
  const {styles} = useStyles();

  return (
    <div className={styles.lang} data-lang>
      {SelectLang && <SelectLang/>}
    </div>
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const {initialState, setInitialState} = useModel('@@initialState');
  const {styles} = useStyles();
  const {message} = App.useApp();
  const intl = useIntl();
  const [form] = Form.useForm();
  const [captcha, setCaptcha] = useState();


  const fetchCaptcha = useDebounceFn(async ( username: string ) => {
    if (!username) {
      setCaptcha(undefined);
      return;
    }
    runCode(username);
  }, {wait: 500});

  const {run: runCode, loading: loadingCode} = useRequest(getCaptcha, {
    manual: true,
    onSuccess: ( data ) => {
      if (data) {
        const {img, uuid} = data;
        setCaptcha(img);
        form.setFieldValue('uuid', uuid);
      }
      else {
        setCaptcha(undefined);
        form.setFieldValue('uuid', null);
      }

    }
  });

  const updateCaptcha = useCallback(() => {
    fetchCaptcha.run(form.getFieldValue('username'));
  }, []);

  useEffect(() => {

  }, []);

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState(( s ) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const handleSubmit = async ( values: API.LoginParams ) => {
    try {
      // 登录
      const res = await login({...values, type});
      if (res.code === 200) {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        setToken(res.data?.token);
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        window.location.href = urlParams.get('redirect') || '/';
        return;
      }
      else {
        message.error(res.message);
      }
      console.log(res);
      // 如果失败去设置用户错误信息
      setUserLoginState(res);
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };
  const {} = userLoginState;

  const getCodeElement = useCallback(() => {
    if (!captcha) {
      return '';
    }
    return (<Flex
      gap="small"
      align="start"
      justify={'space-between'}
      vertical={false}
    >
      <ProFormText
        name="code"
        placeholder={'用于登录关联账号，非必填'}
        formItemProps={{
          className: 'flex-1',
        }}
      />
      <Image
        preview={false}
        width={'80px'}
        height={'32px'}
        src={captcha}
        onClick={updateCaptcha}
        rootClassName="flex-shrink-0"
      />
    </Flex>);
  }, [captcha]);


  const username = Form.useWatch('username', form);
  useEffect(() => {
    fetchCaptcha.run(username);
  }, [username]);

  return (
    <div className={styles.container}>
      <div className={loginStyle.site}></div>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录页',
          })}
          {Settings.title && ` - ${Settings.title}`}
        </title>
      </Helmet>
      <div
        className="flex flex-1 items-center justift-center"
      >
        <LoginForm
          form={form}
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          containerStyle={{
            display: 'block',
            height: 'auto',
            marginTop: -30,
          }}
          logo={<img alt="logo" src="/logo.svg"/>}
          title="Ant Design"
          subTitle={''}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async ( values ) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: intl.formatMessage({
                  id: 'pages.login.accountLogin.tab',
                  defaultMessage: '账户密码登录',
                }),
              },
            ]}
          />

          <>
            <ProFormText name="uuid" hidden></ProFormText>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined/>,
              }}
              initialValue="admin"
              placeholder={intl.formatMessage({
                id: 'pages.login.username.placeholder',
              })}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.username.required"
                      defaultMessage="请输入用户名!"
                    />
                  ),
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined/>,
              }}
              initialValue={'123456'}
              placeholder={intl.formatMessage({
                id: 'pages.login.password.placeholder',
              })}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.password.required"
                      defaultMessage="请输入密码！"
                    />
                  ),
                },
              ]}
            />
            {
              getCodeElement()
            }
          </>
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
